package com.ship.contract.task;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.ship.common.core.domain.R;
import com.ship.common.core.utils.bean.SysFile;
import com.ship.contract.service.ExportService;
import com.ship.common.core.task.ExportTask;
import lombok.Data;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * @author tangshixuan
 * @date 2023-9-6
 */
@Data
public class ExportContractFileTask extends ExportTask {
    /**
     * 源文件路径
     */
    private String filePath;
    /**
     * 起始页
     */
    private int from;
    /**
     * 结束页
     */
    private int end;

    @Override
    public void run() {
        String newFilePath = System.getProperty("java.io.tmpdir") + File.separator + UUID.randomUUID().toString() + ".pdf";
        pdfToSub(this.filePath,newFilePath,this.from,this.end);
        File file = new File(newFilePath);
        MultipartFile multipartFile = getMultipartFile(file);

        R<SysFile> result = null;
        try {
            result = getHttpRequestUtil().upload(multipartFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if(result.getCode() == R.SUCCESS){
            String path = result.getData().getHttpsUrl();
            ((ExportService)getSpringUtil().getBean(ExportService.class)).finish(getExportId(), file,path);
        }
        file.delete();
    }

    public static void pdfToSub(String filePath,String newFile, int from, int end) {
        Document document = null;
        PdfCopy copy = null;
        try {
            PdfReader reader = new PdfReader(filePath);
            //总页数
            int n = reader.getNumberOfPages();
            if (end == 0) {
                end = n;
            }
            document = new Document(reader.getPageSize(1));
            copy = new PdfCopy(document, new FileOutputStream(newFile));
            document.open();
            for (int j = from; j <= end; j++) {
                document.newPage();
                PdfImportedPage page = copy.getImportedPage(reader, j);
                copy.addPage(page);
            }
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }
}
